Synchronization

When using multiple threads, you will sometimes need to coordinate the activities of two or more of the threads. The process by which this is achieved is called synchronization. The most common reason for using synchronization is when two or more threads need access to a shared resource that can be used by only one thread at a time.

Key to synchronization is the concept of a lock, which controls access to a block of code within an object. When an object is locked by one thread, no other thread can gain access to the locked block of code. When the thread releases the lock, the code block is available for use by another thread

Synchronization is supported by the keyword lock.
Syntax:

lock(object
{
     statements to be synchronized
}

 

The effects of lock are:

  1. For any given object, once a lock has been placed on a section of code, the object is locked and no other thread can acquire the lock.
  2. Other threads trying to acquire the lock on the same object will enter a wait state until the code is unlocked.
  3. When a thread leaves the locked block, the object is unlocked.

Program on Synchronization.

using System;
using System.Threading;

class vision
{

    public void put(string s)
{
lock (this)
{
Console.WriteLine("[" + s);
Thread.Sleep(15);
Console.WriteLine("]");
}
}
}

class abc
{
public Thread t;
string s;
vision x;

public abc(string name,vision x)
{
this.x = x;
t = new Thread(this.run);
t.Name = name;
s = name;
t.Start();
}

 
void run()
{
x.put(s);
Console.WriteLine(t.Name + " terminating.");
}
}

class Sync
{
public static void Main()
{

        abc x1, x2, x3;
vision x = new vision();
x1 = new abc("prasad",x);
x2 = new abc("vision",x);
x3 = new abc("Comptuers",x);
x1.t.Join();
x2.t.Join();
x3.t.Join();


}
}